// import { setToken, getToken } from '@/utils/auth.js'
import { setToken, getToken } from '@/utils/auth.js'
import { login } from '@/api/user'

const state = {
  // 登录-初始化token
  token: getToken() || null,
  user: JSON.parse(localStorage.getItem('user')) || {}
}

const mutations = {
// 登录-操作token
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  // 保存个人信息
  userCun(state, user) {
    state.user = user
  }
}

const actions = {
  // 登录-发请求
  async login(context, n) {
    // console.log(context, n)
    const res = await login(n)
    // console.log('actions login', res.data.token.token)
    const token = res.data.token.token
    const user = res.data.user
    localStorage.setItem('user', JSON.stringify(user))
    context.commit('setToken', token)
    context.commit('userCun', user)
  },
  // 退出
  logout(context) {
    localStorage.removeItem('user')
    context.commit('setToken', '')
    context.commit('userCun', {})
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
